/*
 * Main.c
 *
 *  Created on: 25 December 2023
 *      Author: Daniel Mrtensson
 */

#include <stdio.h>

 /* Include Open SAE J1939 */
#include "Open_SAE_J1939/Open_SAE_J1939.h"

int main() {

	/* Create our J1939 structure with two ECU */
	J1939 j1939_1 = { 0 };
	J1939 j1939_2 = { 0 };

	/* Important to sent all non-address to 0xFF - Else we cannot use ECU address 0x0 */
	uint8_t i;
	for (i = 0; i < 255; i++) {
		j1939_1.other_ECU_address[i] = 0xFF;
		j1939_2.other_ECU_address[i] = 0xFF;
	}

	/* Set the ECU address */
	j1939_1.information_this_ECU.this_ECU_address = 0x80;												/* From 0 to 253 because 254 = error address and 255 = broadcast address */
	j1939_2.information_this_ECU.this_ECU_address = 0x90;

	/* Set Proprietary A for ECU 1 */
	j1939_1.this_proprietary.proprietary_A.data[0] = 0x48;												/* H */
	j1939_1.this_proprietary.proprietary_A.data[1] = 0x65;												/* e */
	j1939_1.this_proprietary.proprietary_A.data[2] = 0x6C;												/* l */
	j1939_1.this_proprietary.proprietary_A.data[3] = 0x6C;												/* l */
	j1939_1.this_proprietary.proprietary_A.data[4] = 0x6F;												/* o */
	j1939_1.this_proprietary.proprietary_A.data[5] = 0x20;												/*   */
	j1939_1.this_proprietary.proprietary_A.data[6] = 0x54;												/* T */
	j1939_1.this_proprietary.proprietary_A.data[7] = 0x6F;												/* o */
	j1939_1.this_proprietary.proprietary_A.data[8] = 0x20;												/*   */
	j1939_1.this_proprietary.proprietary_A.data[9] = 0x79;												/* Y */
	j1939_1.this_proprietary.proprietary_A.data[10] = 0x6F;												/* o */
	j1939_1.this_proprietary.proprietary_A.data[11] = 0x75;												/* u */
	j1939_1.this_proprietary.proprietary_A.data[12] = 0x21;												/* ! */
	j1939_1.this_proprietary.proprietary_A.data[13] = 0x0;												/* NULL */
	j1939_1.this_proprietary.proprietary_A.data[14] = 0x0;												/* NULL */

	/* Also set its length */
	j1939_1.this_proprietary.proprietary_A.total_bytes = MAX_PROPRIETARY;
	j1939_2.from_other_ecu_proprietary.proprietary_A.total_bytes = MAX_PROPRIETARY;

	/* ECU 2 sending a request to ECU 1 about Proprietary A - which contains manufacturer specific data */
	SAE_J1939_Send_Request(&j1939_2, 0x80, PGN_PROPRIETARY_A);

	/* Listen for messages */
	for (i = 0; i < 10; i++) {
		Open_SAE_J1939_Listen_For_Messages(&j1939_1);
		Open_SAE_J1939_Listen_For_Messages(&j1939_2);
	}

	/* Print the result */
	printf("%s", (char*)j1939_2.from_other_ecu_proprietary.proprietary_A.data);

	return 0;
}